package corp.edu.amadeus.core.bluetooth.management;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DeviceClass;
import org.apache.log4j.Logger;
import java.util.List;
import java.util.ArrayList;
import corp.edu.amadeus.core.bluetooth.discover.listener.DiscoverListener;
import corp.edu.amadeus.core.bluetooth.wrapper.RemoteDeviceWrapper;


public class DeviceManager {

	private static Logger log = Logger.getLogger(DeviceManager.class);

	private DiscoverListener discover_listener = null;

	private List<RemoteDeviceWrapper> devices = new ArrayList<RemoteDeviceWrapper>();

	private LocalDevice local_device = null;

	private static DeviceManager INSTANCE = null;

	private DeviceManager() {
		this.discover_listener = new DiscoverListener();
		try {
			this.local_device = LocalDevice.getLocalDevice();
			log.debug("---->Local device:  " +
					this.local_device.isPowerOn());
			log.debug("--Bt-address: " +
					this.local_device.getBluetoothAddress());
		} catch (BluetoothStateException e) {
			log.error("Error accesing to local device: " +
					e.getMessage());
			this.local_device = null;
		}
	}

	public List<RemoteDeviceWrapper> getRemoteDevices() {
		List<RemoteDeviceWrapper> devices_replicate =
			new ArrayList<RemoteDeviceWrapper>();
		devices_replicate.addAll(this.devices);
		return devices_replicate;
	}

	public static DeviceManager getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new DeviceManager();
		}
		return INSTANCE;
	}

	public boolean startInquiry() {
		log.debug("---- Inquiry process starting .... ");
		if(this.local_device == null) {
			return false;
		}
		return this.discover_listener.startInquiry();
	}

	public boolean isInquiring() {
		return this.discover_listener.isInquiring();
	}

	public void synchronizeDevices(List<RemoteDeviceWrapper> remote_devices) {
		this.devices.clear();
		this.devices.addAll(remote_devices);
	}

	public void addRemoteDevice(DeviceClass clazz,
			RemoteDevice device) {
		RemoteDeviceWrapper device_w =
			new RemoteDeviceWrapper(clazz, device);
		this.devices.add(device_w);
	}

	public void showRemoteDevices() {
		for (RemoteDeviceWrapper remote_device : this.devices) {
			log.debug("#####################################################");
			log.debug("BluetoothAddress: "
					+ remote_device.getBtAddress());
			log.debug("BluetoothFriendlyName: "
						+ remote_device.getFriendlyName());
			remote_device.showServices();
			log.debug("#####################################################");
		}
	}


}